package controller;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.out;
import static java.lang.System.setOut;

@Controller
public class PointController {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    int t_id;//教师编号

    public PointController() throws IOException {
    }

    //通过试卷id和试题id，判断试卷中是否含该题目
    public boolean isHaveQ_id(int p_id, int q_id) {
        Point p = new Point();
        p.setP_id(p_id);
        p.setQ_id(q_id);
        Point point = sqlSession.selectOne("mapper.Point.findPointById", p);//是否能返回point对象，不为null则存在
        if (point != null) {
            //试卷中已经存在该试题
            return true;
        }
        return false;
    }

    //教师添加试题和对应分数到试卷中
    //新增试题
    @RequestMapping(value = "/addQuestionToPaper", method = RequestMethod.POST)
    public void addQuestionToPaper(@RequestParam(value = "q_id") String q_id, @RequestParam(value = "p_id") String p_id, @RequestParam(value = "one") String one, @RequestParam(value = "two") String two, @RequestParam(value = "three") String three, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        response.setContentType("text/html;charset=utf-8");//设置utf-8
        out.println("addQuestionToPaper获取到的p_id:" + p_id);
        out.println("addQuestionToPaper获取到的单选题分值:" + one);
        Object mess = null;
        String substring = q_id.substring(1, q_id.length() - 1);
        String[] q_ids = substring.split(",");//以逗号为界限对字符串进行分割，得到所有被选择了的试题id
        int length = q_ids.length;
        int[] q_idGroup = new int[length];//创建int型数组，用于存储分割后的转换成int类型的所有试题id
        for (int i = 0; i < q_ids.length; i++) {
            if (q_ids[i] != null && !"".equals(q_ids[i])) {//判断不为空且不为null
                q_idGroup[i] = Integer.parseInt(q_ids[i].trim());//q_id组换成int组
                out.println("转换为int类型后：" + q_idGroup[i]);//输出确认分割获取的所有试题id是否正确，且是否成功转为int
            }
        }
        int rows = 0;
        for (int j = 0; j < q_idGroup.length; j++) {//对于每一道试题
            if (q_idGroup != null) {//判断不为空
                //先判断是否试卷中已经有该题目
                if (isHaveQ_id(Integer.parseInt(p_id), q_idGroup[j])) {
                    out.println("添加了试卷中已经存在的试题\n");
                    mess = "添加失败，选择了试卷中已经存在的试题！";
                    request.getSession().setAttribute("message", mess);
                    response.sendRedirect("loadPaperList");
                    return;
                } else {
                    Point p = new Point();
                    p.setP_id(Integer.parseInt(p_id));//设置每个point行的p_id
                    p.setQ_id(q_idGroup[j]);//设置每个point行的q_id
                    //需要通过q_id获取到试题，判断试题是什么类型
                    Question question = sqlSession.selectOne("mapper.Question.searchQuestionById", q_idGroup[j]);
                    if (question.getQ_type().equals("单选题")) {//题目类型为单选题
                        p.setMark(Float.parseFloat(one));//string转换为float，将获取到的单选题分值赋给该题
                    } else if (question.getQ_type().equals("多选题")) {
                        p.setMark(Float.parseFloat(two));//string转换为float，将获取到的多选题分值赋给该题
                    } else {//题目类型为多选题
                        p.setMark(Float.parseFloat(three));//string转换为float，将获取到的判断题分值赋给该题
                    }
                    //都设置完之后，插入数据
                    rows += sqlSession.insert("mapper.Point.addQuestionToPaper", p);
                    sqlSession.commit();//提交更新数据库
                }
            }
        }//for循环完，插入完毕
        if (rows > 0) {
            out.println("成功添加了" + rows + "个试题！\n");
            Paper get_p_name = sqlSession.selectOne("mapper.Paper.findPaperTimeById", Integer.parseInt(p_id));//根据id获取试卷名称
            sqlSession.commit();
            List<Question> a = sqlSession.selectList("mapper.Point.findQ_idByP_id", Integer.parseInt(p_id));//循环搜索试卷中所有试题，放到session中
            mess = "成功添加了" + rows + "个试题到试卷" + p_id + "中!";
            request.getSession().setAttribute("message", mess);
            session.setAttribute("p_name", get_p_name.getP_name());
            session.setAttribute("questionList", a);
            response.sendRedirect("watch_paper_content.jsp");

        } else {
            out.println("添加失败！\n");
            mess = "添加失败!";
            request.getSession().setAttribute("message", mess);
            response.sendRedirect("loadPaperList");
        }

    }

}
